package edu.pku.hawk.cloud;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.jms.JMSException;

import edu.pku.hawk.cloud.model.XenResource;
import edu.pku.hawk.controller.util.Constants;
import edu.pku.hawk.controller.util.MProducerQueue;
import edu.pku.hawk.controller.util.MQManager;
import edu.pku.hawk.controller.util.SerResourceList;
import edu.pku.taas.hyperic.types2.Cloud;
import edu.pku.taas.hyperic.types2.ResourceTree;

public class ResourceManagerImpl implements ResourceManager {

	public String getResourceXML() {

		System.out.println("get Resource!!!!");
		// return XmlHelper.getXML();
		String result = "";

//		try {
//			result = new ResourceTree().getSerializedCloudResourceTree();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

		return result;
	}

	public List<XenResource> getResourceList() {
		String result = "";
//
//		try {
//			result = new ResourceTree().getSerializedCloudResourceTree();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		// System.out.println("================"+result);
//
//		return XmlHelper.getResources(new ByteArrayInputStream(result
//				.getBytes()));
		return null;
	}

	public List<Cloud> getCloud() {
		List<Cloud> result = new ArrayList<Cloud>();
		Cloud cloud = new ResourceTree().getCloud();
		result.add(cloud);
		return result;
	}

	public void createVM(SerResourceList resource) {
		System.out.println("start vm");
		// resource = new SerResource();
		// resource.setServiceID(100);
		// resource.setServiceName("testService");
		// resource.setCpu(1);
		// resource.setMem(100);
		// resource.setDisk(1);
		// resource.setNet(10);

		MProducerQueue queue = null;

		try {
			queue = MQManager.getInstance().getProducerQueue(
					Constants.Ctrl_Cloud_RscRequest_UI_QueueName);
			queue.send(resource);
		} catch (JMSException e) {
			e.printStackTrace();
		}

	}

	public void responseVMInfor(SerResourceList resource) {
		MProducerQueue queue = null;

		try {
			queue = MQManager.getInstance().getProducerQueue(
					Constants.Ctrl_Cloud_RscResponse_QueueName);
			
			resource.ResourceList = JMSListenner.convertArrayCollection(resource.ResourceList);
			queue.send(resource);
		} catch (JMSException e) {
			e.printStackTrace();
		}

	}

	public void startVM(String vmName) {
		String message = "start:" + vmName;
		sendMessage(message);

	}

	public void stopVM(String vmName) {
		String message = "stop:" + vmName;
		sendMessage(message);
	}

	private void sendMessage(String message) {
		MProducerQueue queue = null;
		try {
			queue = MQManager.getInstance().getProducerQueue(
					Constants.Ctrl_Cloud_RscRequest_UI_QueueName);
			queue.send(message);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
